import user from '../models/user';
import jwt from 'jsonwebtoken';
import bcrypt from 'bcryptjs';
import CONST from '../static/CONST_FILED';
import Response from '../utils/response';

const getUserInfo = async function (ctx) {
  const id = ctx.params.id;
  const result = await user.getUserById(id);
  ctx.body = result;
}

const postUserAuth = async function (ctx) {
  const data = ctx.request.body;
  const userInfo = await user.getUserByName(data.userName);
  if (userInfo != null) {
    if (!bcrypt.compareSync(data.password, userInfo.password)) {
      ctx.body = new Response(null, 500, '密码错误！');
    } else {
      const userToken = {
        userName: userInfo.user_name,
        id: userInfo.id
      }
      const token = jwt.sign(userToken, CONST.JWT_SECRET);
      ctx.body = new Response(token);
    }
  } else {
    ctx.body = new Response(null, 404 , '用户不存在');
  }
}

const postUser = async function(ctx) {
  const data = ctx.request.body;
  console.log(data);
  const userInfo = await user.getUserByName(data.userName);
  if (userInfo === null) {
    const postUserInfo = JSON.parse(JSON.stringify(data));

    postUserInfo.password = bcrypt.hashSync(postUserInfo.password, CONST.SALT_ROUNDS);

    const res = await user.createUser(postUserInfo);

    ctx.body = new Response(res);
  } else {
    ctx.body = new Response(null, 500, '用户名已被注册!');
  }
}

export default {
  getUserInfo,
  postUserAuth,
  postUser
}
